package com.example.pdftoimage;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.pdf.PdfRenderer;
import android.os.Build;
import android.os.ParcelFileDescriptor;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

import android.util.Base64;
import android.util.Log;

import androidx.core.app.ActivityCompat;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import io.dcloud.feature.uniapp.annotation.UniJSMethod;
import io.dcloud.feature.uniapp.bridge.UniJSCallback;
import io.dcloud.feature.uniapp.common.UniModule;

public class TestModule extends UniModule {
    private static final String TAG = "TestModule";
    private static final int PERMISSION_REQUEST_EXTERNAL_STORAGE = 1;

    @UniJSMethod(uiThread = true)
    public void changePdfToImage(String fileUrl, JSONObject options, UniJSCallback callback) {

        JSONArray list = new JSONArray();
        JSONObject result = new JSONObject();

        // 判断fileUrl是否为空
        if (fileUrl == null || fileUrl.isEmpty()) {
            result.put("status", "500");
            result.put("message", "文件路径不能为空");
            result.put("data", list);
            System.out.println("报错参数" + result);
            callback.invoke(result);
            return;
        }

        // 检查options参数,如果options = null || options.isEmpty() || options = {} 则设置默认参数
        if (options == null || options.isEmpty() || options.equals("{}")) {
            options = new JSONObject();
            options.put("quality", 100);
            options.put("format", "JPEG");
        }


        try {
            File pdfFile = new File(fileUrl);
            if (!pdfFile.exists()) {
                result.put("status", "500");
                result.put("message", "文件不存在");
                result.put("data", list);
                System.out.println("报错参数" + result);
                callback.invoke(result);
                return;
            }

            ParcelFileDescriptor parcelFileDescriptor = ParcelFileDescriptor.open(pdfFile, ParcelFileDescriptor.MODE_READ_ONLY);
            PdfRenderer pdfRenderer = new PdfRenderer(parcelFileDescriptor);

            for (int i = 0; i < pdfRenderer.getPageCount(); i++) {
                PdfRenderer.Page page = pdfRenderer.openPage(i);
                Bitmap bitmap = Bitmap.createBitmap(page.getWidth(), page.getHeight(), Bitmap.Config.ARGB_8888);
                Canvas canvas = new Canvas(bitmap);
                canvas.drawColor(Color.WHITE);
                canvas.drawBitmap(bitmap, 0, 0, null);
                page.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
                page.close();
                // 在这里可以将Bitmap转换为图片
                list.add(saveBitmapAsImage(bitmap, i, options));
            }
            pdfRenderer.close();
            parcelFileDescriptor.close();

            result.put("status", "200");
            result.put("message", "转换成功");
            result.put("data", list);
            System.out.println("成功参数" + result);
            callback.invoke(result);
        } catch (IOException e) {
            e.printStackTrace();
            result.put("status", "500");
            result.put("message", "转换失败");
            result.put("data", list);
            System.out.println("报错参数" + result);
            callback.invoke(result);
        }
    }

    /**
     * 将Bitmap转换为base64字符串
     *
     * @param bitmap Bitmap对象
     * @param index  图片索引
     * @return 图片Base64字符串
     */
    private String saveBitmapAsImage(Bitmap bitmap, int index, JSONObject options) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.valueOf(options.getString("format").toUpperCase()), options.getIntValue("quality"), byteArrayOutputStream);
        byte[] byteArray = byteArrayOutputStream.toByteArray();
        return Base64.encodeToString(byteArray, Base64.DEFAULT);
    }


    /**
     * 检查授权
     */
    private void checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // Android M Permission check
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (this.mUniSDKInstance.getContext().checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ((Activity) this.mUniSDKInstance.getContext()).requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_EXTERNAL_STORAGE);
                }
            }
        }
    }
}
